package logic

import (
	"context"
	"errors"
	"goods-master/cache"
	"goods-master/model"
	"goods-master/pkg"

	"goods-master/goodsrpc/goodsrpc"
	"goods-master/goodsrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *goodsrpc.LoginRequest) (*goodsrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user model.User
	result, _ := cache.Rdb.Get(l.ctx, "Captcha"+in.Mobile).Result()
	if result != in.CaptchaCode {
		return nil, errors.New("图形验证码错误")
	}
	result1, _ := cache.Rdb.Get(l.ctx, "sandsms"+in.Mobile).Result()
	if result1 != in.SandsmsCode {
		return nil, errors.New("短信验证码错误")
	}
	err := user.FindUserByMobile(model.DB, in.Mobile)
	if err != nil {
		user.Mobile = in.Mobile
		user.Password = pkg.Str(in.Password)
		err = user.UserAdd(model.DB)
		if err != nil {
			return nil, errors.New("注册失败")
		}
		return nil, err
	}
	if user.Password != pkg.Str(in.Password) {
		return nil, errors.New("密码错误")
	}
	return &goodsrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
